<template>
<!-- 表格组件 -->
<div>
    <el-table border :data="list" style="width: 100%" stripe>
    <el-table-column type="index"></el-table-column>
    <el-table-column prop="username" label="姓名"></el-table-column>
    <el-table-column prop="email" label="邮箱"></el-table-column>
    <el-table-column prop="mobile" label="电话"></el-table-column>
    <el-table-column prop="role_name" label="角色"></el-table-column>
    <el-table-column label="状态" width="120px">
        <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)">
            </el-switch>
        </template>
    </el-table-column>
    <el-table-column label="操作" width="180px">
      <template slot-scope="scope">
        <el-button type="primary" icon="el-icon-edit" size="small" @click="editUp(scope.row.id)"></el-button>
        <el-button type="danger" icon="el-icon-delete" size="small" @click="removeUserId(scope.row.id)"></el-button>
        <el-tooltip content="分配角色" placement="top" :enterable="false">
          <el-button type="warning" icon="el-icon-setting" size="small" @click="castRoles(scope.row)"></el-button>
        </el-tooltip>
      </template>
    </el-table-column>
  </el-table>
          <!-- 修改用户弹出框内容 -->
        <el-dialog title="修改用户" :visible.sync="dialogFormVisible" width="50%" @close="editDialogClosed">
            <el-form label-width="70px" ref="exitFormRef" :rules="editFormRules" :model="editForm">
              <el-form-item label="用户名" prop="username">
                <el-input disabled :value="editForm.username"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="editForm.email"></el-input>
              </el-form-item>
              <el-form-item label="手机" prop="mobile">
                <el-input v-model="editForm.mobile"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUserList">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 分配角色弹出框内容 -->
        <el-dialog
          title="分配角色"
          :visible.sync="setRoleDialogVisible"
          width="50%">
          <p>当前的用户：{{ UserList.username }}</p>
          <p>当前的角色：{{ UserList.role_name }}</p>
          <span>分配新角色：</span>
            <el-select clearable placeholder="请选择" v-model="roleId">
              <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
              </el-option>
            </el-select>
          <span slot="footer" class="dialog-footer">
            <el-button @click="setRoleDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="castRolesId">确 定</el-button>
          </span>
        </el-dialog>
</div>
</template>
<script>
export default {
  props: {
    list: {
      type: Array,
      default () {
        return []
      }
    }
  },
  data () {
    // 验证邮箱的规则
    const checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value) || value === '') {
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    // 验证手机的规则
    const checkMobile = (rule, value, callback) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value) || value === '') {
        return callback()
      }

      callback(new Error('请输入合法的手机号'))
    }
    return {
      // 修改用户框状态
      dialogFormVisible: false,
      // 角色分配显示状态
      setRoleDialogVisible: false,
      // 添加表单效验规则
      editFormRules: {
        email: [
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 点击分配角色框当前的用户数据
      UserList: {},
      // 修改用户数据存放
      editForm: {},
      // 所有角色数据
      rolesList: [],
      // 选中角色ID
      roleId: ''
    }
  },
  methods: {
    // 点击按钮分配角色
    async castRolesId () {
      if (!this.roleId) return this.$message.error('请选择分配角色在提交')
      const { data: res } = await this.$http.put(`users/${this.UserList.id}/role`, { rid: this.roleId })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg || '提交失败')
      this.$message.success(res.meta.msg)
      this.$emit('NewUserList')
      this.setRoleDialogVisible = false
    },
    // 显示分配角色弹出框
    async castRoles (User) {
      this.UserList = User
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg || '请求角色列表失败!')
      this.rolesList = res.data
      this.setRoleDialogVisible = true
    },
    // 打开修改用户弹出框
    // 根据 ID 查询用户信息
    async editUp (Userid) {
      this.dialogFormVisible = true
      const { data: res } = await this.$http.get(`users/${Userid}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editForm = res.data
    },
    // 提交修改数据   并关闭弹出框
    editUserList () {
      this.$refs.exitFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`users/${this.editForm.id}`, this.editForm)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        // 向父组件传一个方法  然后实现重新渲染
        this.$emit('NewUserList')
        this.dialogFormVisible = false
        this.$message.success(res.meta.msg)
      })
    },
    // 删除数据   并关闭弹出框
    async removeUserId (id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('你确定要删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmResult === 'cancel') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`users/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败！')
      this.$message.success('删除用户成功')
      // 向父组件传一个方法  然后实现重新渲染
      this.$emit('NewUserList')
    },
    // 关闭弹出框时重置input内容
    editDialogClosed () {
      this.$refs.exitFormRef.resetFields()
    },
    // 监听 switch 开关状态的改变
    async userStateChanged (userinfo) {
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
    }
  }
}
</script>
